package com.shareach.search.service;

import java.util.HashMap;

import org.codehaus.jackson.type.TypeReference;

import com.shareach.basic.HttpBase;
import com.shareach.basic.ServiceException;
import com.shareach.search.domain.ShopSnatch;
import com.shareach.util.JsonUtil;
import com.shareach.util.URLEncodeUtils;
import com.shareach.web.basic.Answer;


public class DianpingSearcher extends HttpBase {
	private String host;
	public DianpingSearcher(String host){
		this.host = host;
	}

	/**
	 * 匹配商户信息
	 * @param snatchHost
	 * @param city
	 * @param brandName
	 * @param name
	 * @param addr
	 * @param tels
	 * @return
	 */
	public Answer<ShopSnatch> matchShop(String city,String cityName,  String brandName, String name, String addr, String... tels){
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("city", city);
		params.put("cityName", cityName);
		params.put("name", name);
		params.put("brandName", brandName);
		params.put("addr", addr);
		if(tels!=null && tels.length>0){
			String sTel = "";
			for(String s:tels){
				if(sTel.length()>0){
					sTel=","+s;
				}else{
					sTel = s;
				}
			}
			params.put("tel", sTel);
		}
		String json = this.httpPost(host + "/dianping/match.do", params, null);
		return JsonUtil.objectFromJson(json, new TypeReference<Answer<ShopSnatch>>(){});// new TypeRefer)
	}

	/**
	 * @param city 城市点评的代码，必须
	 * @param keyword 查询的关键词，必须进行URLencode，必须。
	 */
	public ShopSnatch search(String city, String keyword){
		StringBuffer sb = new StringBuffer();
		sb.append(host+"/dianping/search.do?city="+city);
		sb.append("&keyword="+URLEncodeUtils.encodeURL(keyword));
		String json =  this.httpGet(sb.toString(),null);
		try{
			Answer<ShopSnatch> jsonResult =JsonUtil.objectFromJson(json, new TypeReference<Answer<ShopSnatch>>(){});
			if(jsonResult.getCode()==0){
				return jsonResult.getResult();
			}else{
				return null;
			}
		}catch(Exception exp){
			throw new ServiceException(-1,"点评搜索错误："+exp.getMessage());
		}
	}
	
	/**
	 * 获取点评的详细信息
	 * @param cityName
	 * @param baiduId
	 * @return
	 */
	public ShopSnatch get(String cityName, String dianpingId){
		StringBuffer sb = new StringBuffer();
		sb.append(host+"/dianping/get.do?id="+dianpingId+"&cityName="+URLEncodeUtils.encodeURL(cityName));
		String json =  this.httpGet(sb.toString(),null);
		try{
			Answer<ShopSnatch> jsonResult =JsonUtil.objectFromJson(json, new TypeReference<Answer<ShopSnatch>>(){});
			if(jsonResult.getCode()==0){
				return jsonResult.getResult();
			}else{
				return null;
			}
		}catch(Exception exp){
			throw new ServiceException(-1,"获取百度详细信息错误："+exp.getMessage());
		}
	}
}
